package NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class SocketClientMain {

    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8080));

        ByteBuffer byteBuffer = ByteBuffer.wrap("12345".getBytes(StandardCharsets.UTF_8));
        socketChannel.write(byteBuffer);

        ByteBuffer readBuff = ByteBuffer.allocate(1024);
        int num;
        if ((num = socketChannel.read(readBuff)) > 0) {
            readBuff.flip();

            byte[] bytes = new byte[num];
            readBuff.get(bytes);

            String read = new String(bytes, "UTF-8");
            System.out.println("返回值:" + read);
        }

        byteBuffer.clear();
        byteBuffer = ByteBuffer.wrap("12".getBytes(StandardCharsets.UTF_8));
        socketChannel.write(byteBuffer);
    }
}
